package com.juneng.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.juneng.common.R;
import com.juneng.config.RedisUtil;
import com.juneng.dto.LoginRequest;
import com.juneng.dto.UserQueryDto;
import com.juneng.entity.User;
import com.juneng.entity.UserAccount;
import com.juneng.service.IUserAccountService;
import com.juneng.service.IUserService;
import com.juneng.utils.MD5Util;
import com.juneng.vo.DashboardResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登入 控制器
 *
 * @author zds
 * @since 2021-07-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/backend/v1")
@Api(tags = "用户登入相关接口")
public class UserLogInController {

    private IUserService iUserService;

    private IUserAccountService iUserAccountService;

    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation(value = "登入", notes = "登入")
    public R<?> doLogin(@RequestBody LoginRequest request) {
        //查询用户是否存在
        UserAccount userAccount = iUserAccountService.getUserAccount(request.getUsername());
        if (userAccount == null) {
            return R.failed("账号不存在");
        } else if (!MD5Util.MD5(request.getPassword()).equals(userAccount.getAccountPwd())) {
            System.out.println(MD5Util.MD5(request.getPassword()));
            System.out.println(userAccount.getAccountPwd());
            return R.failed("密码错误");
        } else {
            //账号密码正确,将账号id存saToken框架
            // StpUtil.setLoginId(userAccount.getUserAccountId());
            // SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            //生成token,存进redis
            String token = IdUtil.simpleUUID();
            redisUtil.set(token, userAccount);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return R.success(map, "登入成功");
        }
    }

    @ApiOperation(value = "登出接口", notes = "登出当前用户")
    @PostMapping("/logout")
    public R<?> logout() {
        // 检验当前会话是否已经登录, 如果未登录，则抛出异常：`NotLoginException`
        StpUtil.checkLogin();
        // 当前会话注销登录
        StpUtil.logout();
        return R.success("退出成功");
    }

    @ApiOperation(value = "登入测试接口", notes = "登出当前用户")
    @PostMapping("/loginType")
    public R<?> loginType() {
        // 获取当前会话是否已经登录，返回true=已登录，false=未登录
        StpUtil.isLogin();
        //
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return R.success(tokenInfo.getTokenValue()) ;
    }

    @GetMapping("/dashboard")
    @ApiOperation(value = "数据概括")
    public R<DashboardResponse> dashboard() {
      return R.success(iUserService.getDashboard()) ;
    }

    public static void main(String[] args) {
        System.out.println(MD5Util.MD5("123456"));
    }
}
